package com.ruoyi.core.config.mp;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.annotation.RateLimiter;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.enums.LimitType;
import com.ruoyi.core.config.utils.WxGptUtil;
import com.ruoyi.core.config.vo.GptLoginVo;
import com.ruoyi.core.domain.vo.UserVo;
import com.ruoyi.core.service.IUserService;
import com.ruoyi.gpt.domain.bo.GptUserBo;
import com.ruoyi.gpt.domain.vo.GptUserVo;
import com.ruoyi.gpt.service.IGptUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotBlank;

/**
 * 微信公众号登录
 */
@RequestMapping("core/chatGpt/{appid}")
@RestController
@RequiredArgsConstructor
@Slf4j
@Validated
public class WxMpGptLoginController extends BaseController {
    private final WxMpService wxMpService;

    private final IGptUserService gptUserService;

    @SaIgnore
    @GetMapping("login")
    @RateLimiter(count = 2, time = 30, limitType = LimitType.IP) // 限流测试 ，同一个ip30秒内只能访问2次
    public R<GptLoginVo> login(@NotBlank(message = "appid不能为空")@PathVariable String appid, @NotBlank(message = "code不能为空") String code) {
        wxMpService.switchoverTo(appid);
        //通过缓存 判断用户
        GptUserVo gptUserVo = WxGptUtil.getUserVoByToken();
        if (ObjectUtil.isNotNull(gptUserVo)) {
            //刷新缓存，
            WxGptUtil.refreshWxUser(gptUserVo, false);
            return R.ok("登录成功",new GptLoginVo(StpUtil.getTokenValue(),gptUserVo ,"0"));
        }
        // 获取用户数据
        WxOAuth2UserInfo userInfo = getUserInfo(code);
        gptUserVo = gptUserService.getByOpenIdAndAppid(userInfo.getOpenid(), appid);
        if(ObjectUtil.isNull(gptUserVo)){
            //保存用户数据
            gptUserVo = gptUserService.setGptUser(appid,userInfo.getUnionId(), userInfo.getOpenid(), "0",userInfo.getNickname(), userInfo.getHeadImgUrl());
            // 执行登录操作
            WxGptUtil.refreshWxUser(gptUserVo,true);

            return R.ok("登录成功",new GptLoginVo(StpUtil.getTokenValue(), gptUserVo ,"1"));
        }else if(ObjectUtil.isNull(gptUserVo.getAvatar())){
            gptUserVo.setAvatar(userInfo.getHeadImgUrl());
            gptUserVo.setNickname(userInfo.getNickname());
            gptUserService.updateByBo(BeanUtil.toBean(gptUserVo, GptUserBo.class));
            // 执行登录操作
            WxGptUtil.refreshWxUser(gptUserVo,true);

            return R.ok("登录成功",new GptLoginVo(StpUtil.getTokenValue(), gptUserVo ,"1"));
        }
        // 刷新缓存
        WxGptUtil.refreshWxUser(gptUserVo,true);
        return R.ok("登录成功",new GptLoginVo(StpUtil.getTokenValue(),gptUserVo ,"0"));
    }

    private WxOAuth2UserInfo getUserInfo(String code){
        try {
            WxOAuth2AccessToken wxOAuth2AccessToken = wxMpService.getOAuth2Service().getAccessToken(code);
            return wxMpService.getOAuth2Service().getUserInfo(wxOAuth2AccessToken, null);
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 获取用户信息
     */
    @GetMapping("getUser")
    public R<GptUserVo> getUser() {
        return R.ok(WxGptUtil.getUserVoByToken());
    }
}
